﻿/*
 * @Author: ws.s 
 * @Date: 2021-09-14 10:30:34 
 * @Last Modified by: ws.s
 * @Last Modified time: 2021-11-04 19:13:53
 */
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using UnityEngine;
using WssUtils;


/// <summary>
/// 存档管理器，管理存档加载读取
/// </summary>
public class SaveManager : Singleton<SaveManager>
{


    /// <summary>
    /// 初始化存档
    /// </summary>
    public void Init()
    {
        this.DeleteAll();
    }

    /// <summary>
    /// 保存存档
    /// </summary>
    /// <param name="key">数据区分key</param>
    /// <param name="data">数据对象</param>
    /// <typeparam name="T">数据类型</typeparam>
    public void Save<T>(string key, T data)
    {
        PlayerPrefs.SetString(key + typeof(T).FullName, JsonConvert.SerializeObject(data));
        // Debug.Log("SAVE JSON:" + key + typeof(T).FullName + ":" + JsonConvert.SerializeObject(data));
    }

    /// <summary>
    /// 读取存档
    /// </summary>
    /// <param name="key">数据区分key</param>
    /// <param name="data">数据对象</param>
    /// <typeparam name="T">数据类型</typeparam>
    public void Load<T>(string key, ref T data)
    {
        var json = PlayerPrefs.GetString(key + typeof(T).FullName);
        var res = JsonConvert.DeserializeObject<T>(json,new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace });
        // Debug.Log("LOAD JSON:" + key + typeof(T).FullName + ":" + json);
        if (res != null) data = res;
    }

    /// <summary>
    /// 检查是否存档
    /// </summary>
    /// <param name="key">数据区分key</param>
    /// <typeparam name="T">数据类型</typeparam>
    /// <returns></returns>
    public bool HasSave<T>(string key)
    {
        var json = PlayerPrefs.GetString(key + typeof(T).FullName);
        return !string.IsNullOrEmpty(json);
    }

    /// <summary>
    /// 数据保存为JSON格式
    /// </summary>
    /// <param name="data">数据对象</param>
    /// <typeparam name="T">数据类型</typeparam>
    /// <returns></returns>
    public string SaveAsJson<T>(T data)
    {
        return JsonConvert.SerializeObject(data);
    }

    /// <summary>
    /// 从JSON 中读取数据
    /// </summary>
    /// <param name="key">数据区分key</param>
    /// <param name="data">数据对象</param>
    /// <param name="jsonData">JSON数据</param>
    /// <typeparam name="T">数据类型</typeparam>
    public void LoadFromJson<T>(string key, ref T data, string jsonData)
    {
        var res = JsonConvert.DeserializeObject<T>(jsonData);
        if (res != null) data = res;
    }

    /// <summary>
    /// 删除清空数据
    /// </summary>
    public void DeleteAll()
    {
        PlayerPrefs.DeleteAll();
    }

    public static long GetTimeStamp()
    {
        System.TimeSpan ts = System.DateTime.Now - new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
        return System.Convert.ToInt64(ts.TotalMilliseconds);
    }

    public static long GetTimeStampOffsetNow(long timeStamp)
    {
        return GetTimeStamp() - timeStamp;
    }



}
